package com.fzy.core.acegi;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.ui.logout.LogoutHandler;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

public class MyLogoutFilter implements Filter {
	
	private static final Log logger = LogFactory.getLog(MyLogoutFilter.class);
	
	private String outSideLoginUrl;
	private String inSideLoginUrl;
	
	private String filterProcessesUrl = "/j_acegi_logout";
	
	private LogoutHandler[] handlers;
	
	public MyLogoutFilter(String outSideLoginUrl,String  inSideLoginUrl,LogoutHandler[] handlers) {
		this.outSideLoginUrl = outSideLoginUrl;
		this.inSideLoginUrl = inSideLoginUrl;
        this.handlers = handlers;
    }
	
	 /**
     * Not used. Use IoC container lifecycle methods instead.
     */
    public void destroy() {}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	        throws IOException, ServletException {
		
		if (!(request instanceof HttpServletRequest)) {
            throw new ServletException("Can only process HttpServletRequest");
        }

        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("Can only process HttpServletResponse");
        }

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        if (requiresLogout(httpRequest, httpResponse)) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            
            UserDetailsImpl detail=(UserDetailsImpl)auth.getPrincipal();
            
            String targetUrl=detail.getVuserFlag().equals("0")?this.inSideLoginUrl:this.outSideLoginUrl;

            if (logger.isDebugEnabled()) {
                logger.debug("Logging out user '" + auth + "' and redirecting to logout page");
            }

            for (int i = 0; i < handlers.length; i++) {
                handlers[i].logout(httpRequest, httpResponse, auth);
            }

            sendRedirect(httpRequest, httpResponse, targetUrl);

            return;
        }
        chain.doFilter(request, response);
	}
	
	 /**
     * Not used. Use IoC container lifecycle methods instead.
     *
     * @param arg0 ignored
     *
     * @throws ServletException ignored
     */
    public void init(FilterConfig arg0) throws ServletException {}

    /**
     * Allow subclasses to modify when a logout should tak eplace.
     *
     * @param request the request
     * @param response the response
     *
     * @return <code>true</code> if logout should occur, <code>false</code> otherwise
     */
    protected boolean requiresLogout(HttpServletRequest request, HttpServletResponse response) {
        String uri = request.getRequestURI();
        int pathParamIndex = uri.indexOf(';');

        if (pathParamIndex > 0) {
            // strip everything after the first semi-colon
            uri = uri.substring(0, pathParamIndex);
        }

        return uri.endsWith(request.getContextPath() + filterProcessesUrl);
    }

    /**
     * Allow subclasses to modify the redirection message.
     *
     * @param request the request
     * @param response the response
     * @param url the URL to redirect to
     *
     * @throws IOException in the event of any failure
     */
    protected void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url)
        throws IOException {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = request.getContextPath() + url;
        }

        response.sendRedirect(response.encodeRedirectURL(url));
    }

    public void setFilterProcessesUrl(String filterProcessesUrl) {
        Assert.hasText(filterProcessesUrl, "FilterProcessesUrl required");
        this.filterProcessesUrl = filterProcessesUrl;
    }

}
